package qsoft.omanga.common.utils;

import android.graphics.Bitmap;
import android.util.Log;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 
 * @author sontt
 * 
 */
public class DownloadImage {

	private static final DownloadImage DOWNLOAD_IMAGE = new DownloadImage();

	public static final DownloadImage getInstance() {
		return DOWNLOAD_IMAGE;
	}

	private static final int POOL_THREADS = 3;
	private final ExecutorService executor = Executors
			.newFixedThreadPool(POOL_THREADS);
	private final Map<String[], TaskDownload> threadDownloads = Collections
			.synchronizedMap(new WeakHashMap<String[], TaskDownload>());

	public void forceDownload(String[] key, Bitmap bitmap) {
		// if (threadDownloads.size() == 0) {
		FileUtil.deleteFileZero(FileUtil.path);
		// }
		String fileName = FileUtil.getImageName(key[0], key[2]);
		if (FileUtil.isExistWithoutExtension(FileUtil.path, fileName)) {
			Log.i("DOWNLOAD ITEM" + key[0], "FILE EXIST...");
			return;
		}
		if (!threadDownloads.containsKey(key)
				|| (threadDownloads.containsKey(key) && !threadDownloads.get(
						key).isAlive())) {
			TaskDownload task = new TaskDownload(key, bitmap);
			task.setPriority(Thread.MIN_PRIORITY);
			threadDownloads.put(key, task);
			executor.submit(task);
			Log.w("DOWNLOAD ITEM" + task.key[0], "INIT THREAD DOWNLOAD...");
		}

	}

	private boolean download(String fullName, Bitmap bitmap) {
		OutputStream os = null;
		try {
			os = new FileOutputStream(fullName + FileUtil.EXTENSION_JPG);
			bitmap.compress(Bitmap.CompressFormat.JPEG, 90, os);
			os.flush();
			os.close();
			return true;
		} catch (FileNotFoundException e) {
			Log.e("FileNotFoundException Item: " + fullName, e.getMessage());
			return false;
		} catch (IOException e) {
			Log.e("IOException Item: " + fullName, e.getMessage());
			return false;
		}
	}

	public class TaskDownload extends Thread {
		private final String[] key;
		private final Bitmap bitmap;

		public TaskDownload(String[] key, Bitmap bitmap) {
			this.key = key;
			this.bitmap = bitmap;
		}

		@Override
		public void run() {
			if (this == threadDownloads.get(key)) {
				String fileName = FileUtil.getImageName(key[0], key[2]);
				String fullName = FileUtil.getNameWithoutExtension(
						FileUtil.path, fileName);
				boolean result = download(fullName, bitmap);
				Log.w("DOWNLOAD Item" + key[0], "RUNNING....");
				if (result) {
					threadDownloads.remove(key);
					Log.i("DOWNLOAD Item" + key[0], "SUCCESS...");
				} else {
					FileUtil.deleteFileWithoutExtension(fullName);
					Log.i("DOWNLOAD Item" + key[0], "FAILURE...");
				}
			}
		}
	}
}
